import {Component, OnInit, ViewEncapsulation} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {ActivatedRoute, Params, Router} from '@angular/router';
import {ValidationService} from '@shared/service/validator/validator.service';
import {Subject} from 'rxjs';
import {AuthService} from "@shared/service/auth/auth.service";
import {MineService} from "@mine/mine.service";
import {ToolsService} from '@shared/service/tools/tools.service';


@Component({
  selector: 'address-form',
  templateUrl: 'address-form.component.html',
  styleUrls: ['address-form.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class AddressFormComponent implements OnInit {
  public type: string;
  public regioObj: any; // 地址省市区数据对象
  public regioStr: string; // 地址省市区字符串
  public showPicker = false; // 有无选择地区
  public isDefaultAddr = 0; // 是否设为默认地址 0不是  1是
  public error = {  // 错误验证的状态
    name: false,
    phone: false,
    address: false,
    detailedAddr: false
  };
  public goodsInfo = { // 商品信息
    skuCode: '',
    quantity: '',
    goodsCateCode: ''
  };
  public haggleInfo = { // 砍价ID 和 砍价发起人ID
    haggleId: 0,
    initiatorId: '',
  };

  public addressForm: FormGroup;
  public ngUnsubscribe: Subject<void> = new Subject<void>();

  constructor(
    public route: ActivatedRoute,
    public router: Router,
    private formBuilder: FormBuilder,
    public authService: AuthService,
    public mineService: MineService,
    private tools: ToolsService
  ) {
    this.route.queryParams
      .subscribe((param: Params) => {
        this.haggleInfo.haggleId = param['haggleId'];
        this.haggleInfo.initiatorId = param['initiatorId'];
      });
  }

  /**
   * @description  设置标题
   * @author ouyqx-691
   * type:update(修改)
   * type:insert(新增)
   */
  setTitle() {
    this.route.queryParams.takeUntil(this.ngUnsubscribe).subscribe((params: Params) => {
      this.type = params['type'];
      const goodsInfo = this.goodsInfo;
      goodsInfo.skuCode = params['skuCode'];
      goodsInfo.quantity = params['quantity'];
      goodsInfo.goodsCateCode = params['goodsCateCode'];
    });
  }

  // 表单初始化
  formInit() {
    this.addressForm = this.formBuilder.group({
      'name': ['', [Validators.required, Validators.minLength(2), ValidationService.nickNameValidator]],
      'phone': ['', [Validators.required, ValidationService.accountValidator]],
      'detailedAddr': ['', [Validators.required]]
    });
  }

  // 表单单项输入错误提示
  nameCheck() {
    if (!this.addressForm.controls['name'].valid && this.addressForm.controls['name'].dirty) {
      this.error.name = true;
    } else {
      this.error.name = false;
    }
  }

  // 手机号错误提示
  phoneCheck() {
    if (!this.addressForm.controls['phone'].valid && this.addressForm.controls['phone'].dirty) {
      this.error.phone = true;
    } else {
      this.error.phone = false;
    }
  }

  // 详细地址错误提示
  detailedAddrCheck() {
    if (!this.addressForm.controls['detailedAddr'].valid && this.addressForm.controls['detailedAddr'].dirty) {
      this.error.detailedAddr = true;
    } else {
      this.error.detailedAddr = false;
    }
  }


  /**
   * @description  处理地区选择
   * @author ouyqx-691
   */
  handleRegioPicker(result) {
    this.regioObj = result;
    this.regioStr = result.provinceName + result.cityName + result.districtName;
    ;
    this.showPicker = false;
    this.error.address = false;
  }

  /**
   * @description  处理是否设为默认地址
   * @author ouyqx-691
   */
  handleSwitch(e) {
    const isChecked = e.target.checked;
    isChecked ? this.isDefaultAddr = 1 : this.isDefaultAddr = 0;
  }

  /**
   * @description  提交表单
   * @author ouyqx-691
   */
  submitForm() {
    if (!this.regioStr) {
      this.error.address = true;
      return;
    }
    const regioObj = this.regioObj;
    const formData = this.addressForm.controls;

    const data = {
      userId: this.authService.getUserId(),
      consignee: formData.name.value, // 收货人
      mobile: formData.phone.value, // 收货人手机号
      prov: regioObj.provinceId, // 省ID
      city: regioObj.cityId, // 市ID
      dist: regioObj.districtId, // 区县ID
      detailAddress: formData.detailedAddr.value, // 详细地址
      isDefaultAddress: this.isDefaultAddr // 是否设为默认地址
    };
    this.mineService.postNewAdress(data).subscribe(res => {
      if (res.result === '0') {
        const goodsInfo = this.goodsInfo;
        this.router.navigate(['/mine/address/list'], {
          queryParams: {
            haggleId: this.haggleInfo.haggleId,
            initiatorId: this.haggleInfo.initiatorId,
            skuCode: goodsInfo.skuCode,
            quantity: goodsInfo.quantity,
            goodsCateCode: goodsInfo.goodsCateCode
          }
        });
      } else {
        this.tools.showToast(res.msg);
      }
    });
  }

  ngOnInit() {
    this.setTitle();
    this.formInit();
  }
}
